package com.tomecode.mjprocessor;

import java.io.File;

import org.apache.maven.model.Model;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

import com.tomecode.mjprocessor.assembly.Assembly;
import com.tomecode.mjprocessor.assembly.AssemblyReader;
import com.tomecode.mjprocessor.assembly.type.ProjectActions;
import com.tomecode.mjprocessor.execute.AssemblyExecutor;
import com.tomecode.mjprocessor.execute.MJProcessorException;
import com.tomecode.mjprocessor.execute.ProjectNotFoundException;
import com.tomecode.mjprocessor.util.MavenResolver;

/**
 * 
 * Maven java processor , simple maven plugin which  
 * 
 * @author Frastia Tomas
 * @goal execute
 */
public class MavenJavaProcessor extends AbstractMojo {

	/**
	 * file which contain processor-description
	 * 
	 * @parameter
	 */
	private File configFile;
	/**
	 * defines list of profiles which will be executed on this artifact, These
	 * profiles must be equal to {@link ProjectActions#getProfile()}
	 * 
	 * @parameter
	 */
	private String[] profiles;

	/**
	 * @parameter default-value ="${basedir}"
	 */
	private File baseDir;

	public final void execute() throws MojoExecutionException, MojoFailureException {
		getLog().info("config file: " + configFile);

		try {
			Model model = MavenResolver.getModel(baseDir);
			String groupId = model.getGroupId();
			if (groupId == null) {
				groupId = model.getParent().getGroupId();
			}
			getLog().info("------------> execute processor for:");
			getLog().info("groupId:" + groupId);
			getLog().info("artifactId:" + model.getArtifactId());
			getLog().info("------------>");

			Assembly assembly;
			AssemblyReader assemblyReader = new AssemblyReader(baseDir);
			assembly = assemblyReader.parse(configFile);
			AssemblyExecutor assemblyExecutor = new AssemblyExecutor(getLog(), assembly, MavenResolver.loadProperties(model, baseDir));
			assemblyExecutor.execute(groupId, model.getArtifactId(), profiles);
		} catch (ProjectNotFoundException e) {
			getLog().error(new MojoExecutionException("Not found project " + e.getMessage() + " in config file: " + configFile, e));
		} catch (MJProcessorException e) {
			getLog().error(new MojoExecutionException(e.getMessage(), e));
		} catch (Exception e) {
			getLog().error(new MojoExecutionException(e.getMessage(), e));
		}
	}
	
	
}
